# -*- mode: python ; coding: utf-8 -*-

import os
import sys
import platform
from pathlib import Path

# 项目根目录是packaging文件夹的上级目录
project_root = Path(SPECPATH).parent

# 应用信息
app_name = "HQ-Reader"
app_version = "1.0.0"

# 平台检测
is_windows = platform.system() == "Windows"
is_macos = platform.system() == "Darwin"
is_linux = platform.system() == "Linux"

# 运行字体缓存构建脚本
import subprocess
try:
    print("构建Matplotlib字体缓存...")
    font_cache_script = project_root / "scripts" / "build_font_cache.py"
    if os.path.exists(font_cache_script):
        subprocess.run([sys.executable, str(font_cache_script)], check=True)
        print("字体缓存构建完成")
    else:
        print(f"警告: 字体缓存构建脚本不存在: {font_cache_script}")
except Exception as e:
    print(f"警告: 字体缓存构建失败: {e}")

# 数据文件和隐藏导入
datas = [
    (str(project_root / "config"), "config"),
    (str(project_root / "translations"), "translations"),
    (str(project_root / "assets"), "assets"),
    (str(project_root / "ui"), "ui"),
]

# 添加matplotlib字体缓存目录（如果存在）
matplotlib_cache_dir = project_root / "assets" / "matplotlib_cache"
if os.path.exists(matplotlib_cache_dir):
    datas.append((str(matplotlib_cache_dir), "matplotlib_cache"))

# 隐藏导入 - PySide6和其他必要模块
hiddenimports = [
    'PySide6.QtCore',
    'PySide6.QtWidgets', 
    'PySide6.QtGui',
    'PySide6.QtSql',
    'duckdb',
    'pyarrow',
    'sqlparse',
    'chardet',
    'matplotlib',
    'matplotlib.backends.backend_qt5agg',
    'seaborn',
    'psutil',
    'openpyxl',
    'cairosvg',
    'dotenv',
    'pkg_resources.py2_warn',
    # jaraco相关模块
    'jaraco.text',
    'jaraco.functools',
    'jaraco.context',
    'autocommand',
    'more_itertools',
    'backports.tarfile',
    # 其他依赖
    'platformdirs',
]

# 平台特定的隐藏导入
if is_macos:
    hiddenimports.extend([
        'PySide6.QtMacExtras',
        'matplotlib.backends.backend_macosx',
    ])
elif is_windows:
    hiddenimports.extend([
        'PySide6.QtWinExtras',
        'matplotlib.backends.backend_tkagg',
    ])

# 排除的模块
excludes = [
    'tkinter',
    'unittest',
    'test',
    'distutils',
    'setuptools',
    'pip',
]

# 图标文件
icon_file = None
if is_windows:
    icon_file = str(project_root / "assets" / "icons" / "icon.ico")
elif is_macos:
    icon_file = str(project_root / "assets" / "icons" / "icon.icns")

# PyInstaller分析
a = Analysis(
    [str(project_root / 'main.py')],
    pathex=[str(project_root)],
    binaries=[],
    datas=datas,
    hiddenimports=hiddenimports,
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=excludes,
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=None,
    noarchive=False,
)

# 移除重复文件
pyz = PYZ(a.pure, a.zipped_data, cipher=None)

# 可执行文件配置 - 使用onedir模式确保所有依赖都被包含
exe = EXE(
    pyz,
    a.scripts,
    [],  # 不使用 a.binaries 和 a.datas，让它们保持在目录中
    exclude_binaries=True,  # 关键：排除二进制文件，使用onedir模式
    name=app_name,
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    console=False,  # 不显示控制台窗口
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
    icon=icon_file if icon_file and os.path.exists(icon_file) else None,
)

# 收集所有文件到目录中
coll = COLLECT(
    exe,
    a.binaries,
    a.zipfiles,
    a.datas,
    strip=False,
    upx=True,
    upx_exclude=[],
    name=app_name,
)

# macOS应用程序包
if is_macos:
    app = BUNDLE(
        coll,  # 使用 coll 而不是 exe
        name=f'{app_name}.app',
        icon=icon_file,
        bundle_identifier=f'com.hqreader.{app_name.lower()}',
        version=app_version,
        info_plist={
            'CFBundleName': app_name,
            'CFBundleDisplayName': app_name,
            'CFBundleVersion': app_version,
            'CFBundleShortVersionString': app_version,
            'CFBundleIdentifier': f'com.hqreader.{app_name.lower()}',
            'CFBundleExecutable': app_name,
            'CFBundlePackageType': 'APPL',
            'CFBundleSignature': 'HQRD',
            'NSHighResolutionCapable': True,
            'NSRequiresAquaSystemAppearance': False,
            'LSMinimumSystemVersion': '10.14',
            'NSHumanReadableCopyright': f'Copyright © 2024 HQ-Reader Team. All rights reserved.',
            'CFBundleDocumentTypes': [
                {
                    'CFBundleTypeName': 'CSV File',
                    'CFBundleTypeExtensions': ['csv'],
                    'CFBundleTypeRole': 'Viewer',
                    'CFBundleTypeIconFile': 'icon.icns',
                },
                {
                    'CFBundleTypeName': 'Parquet File', 
                    'CFBundleTypeExtensions': ['parquet'],
                    'CFBundleTypeRole': 'Viewer',
                    'CFBundleTypeIconFile': 'icon.icns',
                },
            ],
        },
    ) 